<?php
//表单实例，包括所有字段和附加功能
function get_form($table)
{
    if ($form = config("tables.$table.form")) {
        return $form;
    } else {
        $form = [];
        $fields = get_table_fields($table);
        foreach ($fields as $k => $val) {
            if ($val == 'id') {
                $form[$val] = ['display' => 'ID'];
            } else {
                $form[$val] = ['text' => ucfirst($val)];
            }
        }
        return $form;
    }
}
//新建表单
function get_create_form($table)
{
    $form   = get_form($table);
    $ignore = config("tables.$table.form.form_create_ignore") ?? [];
    return array_intersect_key($form, array_flip($ignore));
}
//编辑表单
function get_update_form($table)
{
    $form = get_form($table);
    $update_replace = config("tables.$table.form.form_update_replace") ?? [];
    $form = array($form, $update_replace);
    $ignore = config("tables.$table.form.form_update_ignore") ?? [];
    return array_intersect_key($form, array_flip($ignore));
}
//字段名解释
function get_comments($table)
{
    $comments = [];
    $fields = config("tables.$table.form") ?? [];
    foreach ($fields as $key => $value) {
        if (is_numeric($key) || !is_array($value) || empty($value)) continue;
        $comments[$key] = ['type' => key($value), 'title' => array_shift($value)];
    }
    return $comments;
}
//index字段
function get_grid($table)
{
    $fields = config("tables.$table.grid_fields") ?? [];
    if (empty($fields)) {
        $fields = get_table_fields($table);
    }
    $comments = get_comments($table);
    $grids = [];
    foreach ($fields as $key => $value) {
        $grids[$value] = empty($comments[$value]) ? ['type' => 'text', 'title' => ucfirst($value)] : $comments[$value];
    }
    return $grids;
}
//详细字段
function get_show($table)
{
    $fields = config("tables.$table.show_fields") ?? get_table_fields($table);
    $form = get_form($table);
    $shows = array_intersect_key($form, array_flip($fields));
    return $shows;
}

if (!function_exists('get_module')) {
    function get_module($mslug)
    {
        $mslug = explode('.', $mslug);
        if (count($mslug) > 1) {
            $location = $mslug[0];
            $module = $mslug[1];
        } else {
            $location = config('modules.default_location');
            $module = $mslug[0];
        }
        return (Module::location($location)->where('slug', $module))->toArray();
    }
}

if (!function_exists('get_module_slug')) {
    function get_module_slug($mslug)
    {
        $mslug = explode('.', $mslug);
        if (count($mslug) > 1) {
            return $mslug[1];
        } else {
            return $mslug[0];
        }
    }
}

if (!function_exists('get_module_by_model')) {
    function get_module_by_class($mslug = '')
    {
        $locations = config("modules.locations");
        foreach ($locations as $k => $location) {
            if (strpos($mslug, $location['namespace']) === 0) {
                $arr = explode('\\', ltrim($mslug, $location['namespace']));
                $name = \Str::slug($arr[0]);
                return get_module($k . '.' . $name);
            }
        }
        return false;
    }
}
if (!function_exists('get_image')) {
    /**
     *
     * @return string
     */
    function get_image($img = '')
    {
        $ext = pathinfo($img, PATHINFO_EXTENSION);
        if (!in_array(strtolower($ext), ['jpg', 'jpeg', 'png', 'bmp', 'gif'])) return get_nopic();
        if (file_exists(config('filesystems.disks.local.root') . '/' . $img)) {
            return config('filesystems.disks.local.url') . '/' . $img;
        } else {
            return get_nopic();
        }
    }
}

if (!function_exists('get_nopic')) {
    function get_nopic()
    {
        return config('filesystems.disks.local.url') . '/nopic.jpg';
    }
}

if (!function_exists('uuid')) {
    /**
     * Generate a UUID (version 4).
     *
     * @return string
     */
    function uuid(): string
    {
        return \Illuminate\Support\Str::uuid()->toString();
        // 或直接 \Ramsey\Uuid\Uuid::uuid4()->toString();
    }
}

if (!function_exists('str2arr')) {
    /**
     * 字符串转换为数组，主要用于把分隔符调整到第二个参数
     * @param  string $str  要分割的字符串
     * @param  string $glue 分割符
     * @return array
     */
    function str2arr($str = '', $glue = ',', $len = null)
    {
        if ($str) {
            if (is_array($str)) {
                return $str;
            } elseif ($len) {
                return explode($glue, $str, $len);
            } else {
                return explode($glue, $str);
            }
        } else {
            return array();
        }
    }
}

if (!function_exists('arr2str')) {
    /**
     * 数组转换为字符串，主要用于把分隔符调整到第二个参数
     * @param  array  $arr  要连接的数组
     * @param  string $glue 分割符
     * @return string
     */
    function arr2str($arr = array(), $glue = ',')
    {
        if (empty($arr)) {
            return '';
        } else {
            if (is_array($arr)) {
                return implode($glue, $arr);
            } else {
                return $arr;
            }
        }
    }
}

if (!function_exists('tag2arr')) {
    /**
     * 数组转换为字符串，主要用于把分隔符调整到第二个参数
     * @param  array  $arr  要连接的数组
     * @param  string $glue 分割符
     * @return string
     */
    function tag2arr($tag)
    {
        $tag = str2arr($tag);
        $arr = [];
        foreach ($tag as $v) {
            $arr[$v] = $v;
        }
        return $arr;
    }
}

if (!function_exists('get_table_fields')) {
    function get_table_fields($table, $refrech = false)
    {
        if ($refrech || empty(\Illuminate\Support\Facades\Cache::get('table-fields-' . $table))) {
            $fields = \Illuminate\Support\Facades\Schema::getColumnListing($table);
            \Illuminate\Support\Facades\Cache::forever('table-fields-' . $table, $fields);
        } else {
            $fields = \Illuminate\Support\Facades\Cache::get('table-fields-' . $table);
        }
        return $fields;
    }
}
if (!function_exists('json_response')) {
    /**
     * Return a new JSON response.
     *
     * @param  string|array  $data
     * @param  int  $status
     * @param  array  $headers
     * @param  int  $options
     * @return \Illuminate\Http\JsonResponse
     */
    function json_response($data = [], $status = 200, array $headers = [], $options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
    {
        if (!isset($data['data'])) {
            $ndata['data'] = $data;
            $data = $ndata;
        }
        if ($status >= 400) {
            $ext['status'] = $ext['status'] ?? 0;
        } else {
            $ext['status'] = $ext['status'] ?? 1;
        }
        $ext['code'] = $status;
        $ext['url'] = $ext['url'] ?? request()->getRequestUri();
        $data = array_merge($ext, $data);
        return new \Illuminate\Http\JsonResponse($data, $status, $headers, $options);
    }
}
if (!function_exists('json_error')) {
    /**
     * Return a new error (4xx) response.
     *
     * @param  string  $message
     * @param  array  $errors
     * @param  int  $code
     * @return \Illuminate\Http\JsonResponse
     */
    function json_error($errors = '', $code = 400)
    {
        $data = [];
        return json_response(compact('data', 'errors'), $code);
    }
}
if (!function_exists('json_ok')) {
    /**
     * Return an all json_ok 200 response.
     * 响应正常
     * @param  mixed  $data
     * @return \Illuminate\Http\JsonResponse
     */
    function json_ok($data = null)
    {
        if (is_string($data)) {
            $data['message'] = $data;
        }
        return json_response($data, 200);
    }
}
if (!function_exists('created')) {
    /**
     * Return created response.
     * 服务器在请求的响应中建立了新文档
     * @param  mixed  $data
     * @return \Illuminate\Http\JsonResponse
     */
    function created($data = null)
    {
        $data['status'] = 1;
        return json_response($data, 201);
    }
}
if (!function_exists('accepted')) {
    /**
     * Return accepted response.
     * 服务器已接受请求,但尚未处理
     * @param  mixed  $data
     * @return \Illuminate\Http\JsonResponse
     */
    function accepted($data = null)
    {
        return json_response($data, 202);
    }
}
if (!function_exists('no_content')) {
    /**
     * Return no content response.
     * 无内容,对于一些提交到服务器处理的数据,只需要返回是否成功的情况下,可以考虑使用状态码204来作为返回信息
     * @return \Illuminate\Http\JsonResponse
     */
    function no_content()
    {
        return json_response(null, 204);
    }
}
if (!function_exists('bad_request')) {
    /**
     * Return a bad request response.
     * 请求错,表示语义有误,当前请求无法被服务器理解
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function bad_request($errors = '请求错')
    {
        return json_error($errors, 400);
    }
}
if (!function_exists('unauthenticated')) {
    /**
     * Return a unauthenticated response.
     * 无权限,需要进行身份认证
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function unauthenticated($errors = '无权限')
    {
        return json_error($errors, 401);
    }
}
if (!function_exists('forbidden')) {
    /**
     * Return a forbidden response.
     * 禁止(资源不可用),服务器理解客户的请求，但拒绝处理它
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function forbidden($errors = '资源不可用')
    {
        return json_error($errors, 403);
    }
}
if (!function_exists('not_found')) {
    /**
     * Return a not found response.
     * 404
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function not_found($errors = '未找到')
    {
        return json_error($errors, 404);
    }
}
if (!function_exists('method_not_allowed')) {
    /**
     * Return a method not allowed response.
     * 不允许的请求方式
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function method_not_allowed($errors = '不允许的请求方式')
    {
        return json_error($errors, 405);
    }
}
if (!function_exists('not_acceptable')) {
    /**
     * Return a not acceptable response.
     * 不接受(后台的返回结果前台无法解析)
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function not_acceptable($errors = '返回结果无法解析')
    {
        return json_error($errors, 406);
    }
}
if (!function_exists('teapot')) {
    /**
     * All hail the magical teapot response.
     * 当客户端给一个茶壶发送泡咖啡的请求时，茶壶就返回一个418错误状态码，表示“我是一个茶壶”
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function teapot($errors = '请求对象错误')
    {
        return json_error($errors, 418);
    }
}
if (!function_exists('unprocessable_entity')) {
    /**
     * Return a unprocessable entity response.
     * 请求格式正确,但是由于含有语义错误,无法响应（无法处理的实体）
     * @param  string  $message
     * @param  array  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    function unprocessable_entity($errors = '无法处理的实体')
    {
        return json_error($errors, 422);
    }
}
